Today we will go through a series of steps that are familiar to many scientist doing empirical work. We will pretend to have collected some data1, clean them, visualize them, and analyze them using common statistical models. We will do all these things with the tidyverse, a collection of R packages for data manipulation and plotting that aims at being easily readable not only for machines, but also for humans2. These operations will be run in an environment that ensures computational reproducibility: if you have the initial data set, you will be able to reproduce the final results with a mouse click.

On your computer, you should already have installed R and RStudio (if not, follow the instructions for your operating system here and here).

Setup

One possible way to work on a project is to open a new .R file and write your code there. However, there are a few disadvantages:

  • your collaborators may not have your same folder structure, i.e., where you store data and code
    • you could specify a working directory with setwd(), e.g., setwd("NAME/OF/YOUR/DIRECTORY")
  • you cannot know the state of your collaborators’ working environment, e.g., what functions or packages they have already loaded
    • you could include, at the beginning of your script, the following lines:
      • cat("\014") to clear the console
      • rm(list = ls()) to clear the environment (but it does not unload active packages!)

You could do all those things, but… should you?

Jenny Bryan explains the reasons (without threats to commit arson) in this blog post. The main idea is to package code in a self-contained environment that everyone (including your future self) can run without changing their own environment.

R Projects

Following Jenny Brian’s suggestion (and to avoid her wrath) we can create a project directly from RStudio:

  • click the “File” menu button, then “New Project”
  • click “New Directory”
  • click “New Project”
  • type in the name of the directory to store your project, e.g., “YOURNAME_ERIM2020_intro_tidyverse”
  • click the “Create Project” button

If you check the directory you just created, you will see a file called YOURNAME_ERIM2020_intro_tidyverse.Rproj. If your RStudio session is still open, look at the top of the active window: the R Project is already active.

Install Packages

It is time to install the first package of this session: here3. For a brief overview of what the package can do, see this GitHub repository (authored by Jenny Bryan!).

Once the package is installed, we can load it:

This package is very useful to keep raw data, analysis scripts, preprocessed data, and reports in separate subdirectories (which is what you should always aim for). In which directory are we now?

## [1] "/home/aschetti/Documents/Projects/ERIM2020_intro_tidyverse"

We are now in the directory of the .Rproj file. However, our data are in a subdirectory called raw-data. here allows you to link to that directory without actually going there.

## [1] "/home/aschetti/Documents/Projects/ERIM2020_intro_tidyverse/raw-data"

In other words, we are still inside our R Project directory (/home/aschetti/Documents/Projects/ERIM2020_intro_tidyverse) but we can load and save files inside the respective subfolders.

Let’s verify that the data we need are actually in the raw-data subdirectory:

## [1] "MixedAttitude.dat"

Yes, the file MixedAttitude.dat is what we are going to play with today.

Exercise 1

Install and load the tidyverse.

Data manipulation

The data are in .dat format… how can we load them?4 The function read_csv from the readr package (part of the tidyverse) can load this kind of tab-separated files:

## Parsed with column specification:
## cols(
##   ssj = col_double(),
##   sex = col_double(),
##   beerpos = col_double(),
##   beerneg = col_double(),
##   beerneut = col_double(),
##   winepos = col_double(),
##   wineneg = col_double(),
##   wineneut = col_double(),
##   waterpos = col_double(),
##   waterneg = col_double(),
##   waterneu = col_double()
## )

For additional details on the arguments of this function, type ?read_csv in the console.

Now the data are in a tibble, the equivalent of a data.frame in the tidyverse. Type att (the name of the data set in our environment) in the console to see the first cases.

To see the full data set, click on att in the Environment window (by default on the upper right corner).

These are the data of 22 participants who saw neutral, positive, or negative advertisement of beer, wine, and water in 3 separate sessions. They were asked to rate the drinks on a scale ranging from –100 (dislike very much) through 0 (neutral) to +100 (like very much). Researchers wanted to reduce binge drinking in teenagers, so they hoped that pairing negative imagery with alcoholic beverages would lower these ratings5.

When the data set is big, it is useful to have a general idea of what it contains (tip: use the function glimpse).

Filtering

Looking at the data, two things stand out:

  1. data of participant #98 are implausible, perhaps due to technical problems (e.g., the rating scale was out of the -100/100 range)
  2. data of participant #99 contains missing values (NA)

We need to eliminate these two participants from the data. Let’s start from participant #98.

Here we keep all participants that are not participant #98 (!= operator). The symbol %>% is the pipe operator, which allows to serially concatenate functions applied to the same data frame. Read it as “and then”. In the example above, we called the data frame att and then applied the filter function to discard participant #98.

How to verify that the filtering worked? You could click on att in the Environment window and look for participant #98, but it can be tedious with big data sets. An easy and flexible way is to check if the filtered data set still contains participant #98:

The tibble is empty, confirming the deletion.

Now let’s think of participant #99.

The code above allows us to keep all rows whose values of the variable waterneu are not NAs. Did it work?

It worked! We could also apply both filters simultaneously using the & (AND) operator:

However, with large data sets, it is unfeasible to visually check all values of all variables of all participants to see if something went wrong during data collection. A better strategy is to use the knowledge we already have about the experimental design. In this case, we know that ratings were collected via scales ranging from -100 to +100, so anything below -100 or above +100 should not be analyzed. Here we decide to only keep participants whose values of the variable waterneu are within the aforementioned range:

This strategy allows us to simultaneously get rid of both participant #98 and #99.

Variable selection

For today’s exercises, we will only need a subset of variables in this data set.

Researchers were interested in reducing binge drinking, so we will focus our attention on negative imagery and one alcoholic beverage. We choose beer. We also need control conditions, i.e., neutral imagery and water.

In the next code snippet, we simultaneously select and rename the variables we want to keep.

Recoding

Let’s inspect the variable sex:

##  [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2

A string of 1s and 2s. It’s easy to get a glimpse of the unique values of this variable because there are not many observations. When you have more observations, better use the function unique:

## [1] 1 2

What type of variable is it?

## [1] "numeric"

Class numeric has numeric values (i.e., double precision floating point numbers).

There are many variable types in R. An interesting one is factor, i.e., categorical variables. In our case, it would make sense to consider sex as a factor with two levels, male and female. Let’s transform it:

Now we have two variables with redundant information… let’s get rid of sex:

Pivoting

Data frames can be in wide or long format:

  • wide format: participants as rows, conditions as columns (e.g., SPSS)
  • long format: every row represents an observation belonging to a particular condition

Our data are now in wide format. However, the packages we are going to use today need data in long format. Let’s convert from wide to long:

The column ratings contains the values of our dependent variable, whereas condition contains all our conditions.

This experiment has two independent variables, drink and imagery. In our analysis, we wish to know the separate contribution of these two independent variables as well as their interaction. So, we need to separate the variable condition into 2 columns:

Saving

The original data are saved in a .dat file. Instead, we will save our processed data as .csv.

Concatenate operations

Thanks to the versatility of the tidyverse (especially the pipe operator), all the above operations can be performed in one go:

Are the two data sets really identical? Verify with the all_equal function:

## [1] TRUE

Summary

It is often required to provide summary statistics of the data. How to do it in tidyverse?

## # A tibble: 4 x 8
##   drink imagery      n  mean    sd   sem   min   max
##   <fct> <fct>    <int> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 beer  negative    20  4.45 17.3   3.87   -19    30
## 2 beer  neutral     20 10    10.3   2.30   -10    28
## 3 water negative    20 -9.2   6.80  1.52   -20     5
## 4 water neutral     20  2.35  6.84  1.53   -13    12

Exercise 2

Exercise 2.1

Do the following operations in one go:

  • load the original data (MixedAttitude.dat)
  • convert sex to a categorical variable (named gender) with 2 levels:
    • 1 –> female
    • 2 –> male
  • eliminate from the data set the following variables: sex, beerpos, beerneg, beerneut, winepos, and waterpos
  • using the function rename, rename the variables you kept:
    • ssj –> participant
    • wineneg –> wine_negative
    • wineneut –> wine_neutral
    • waterneg –> water_negative
    • waterneu –> water_neutral
  • filter out outlier participants as well as all participants who rated water after neutral imagery as lower than -10
  • convert the data set to long format
  • separate conditions into 2 variables (drink and imagery)
  • convert participant, gender, drink, and imagery to factors

When you have completed these operations, save the data set as data_attitude_wine.csv in the subfolder tidy-data.

Exercise 2.2

Using the output of Exercise 2.1:

  • separately for gender, drink, and imagery, calculate the following summary statistics:
    • number of observations
    • median
    • median absolute deviation
    • minimum value
    • maximum value
  • display the results in console

Plotting

Plotting is one of the most satisfying things to do in R, especially if you use the package ggplot2… part of the tidyverse! In a nutshell, ggplot2 allows you to build plots iteratively using a series of layers. You start with a data set and specify its aesthetics (e.g., which variable should be represented on the x-axis?). Later, you can add layers with annotations, statistical summaries, and so on.

Bar plot

Let’s start by creating a basic bar plot. We will use the data frame with the summary statistics that we just created (summary_att_filter_select_recode_long_sep_onego).

What the hell is that?!? Oh no, it’s a stacked bar graph! We don’t want that! How can we get separate bars for negative and neutral imagery?

Better. Let’s add outlines.

Something is missing… ah, error bars! Display the standard deviation.

These colors are terrible… let’s use a more decent color palette. The package viridis uses colors that are easier to distinguish for people with colorblindness.

Let’s add a final cosmetic touch.

RDI plots

No matter how pretty a bar graph is, it remains a suboptimal way of displaying your data.
A better solution is to use RDI plots.

RDI plots display Raw data, Descriptives, and Inferential statistics altogether. Nothing is hidden by useless bars, everything is shown so that readers can make up their minds. For example, the violin plot6 below shows:

  • points: individual data
  • vertical bars: means
  • boxes: 95% confidence intervals (assuming a normal sampling distribution)
  • smoothed densities

To build it, we need to install ggpirate, which provides handy functions to create violin plots.

As you can see, we installed ggpirate in a different way: we used the function install_github from the package devtools. That’s because ggpirate is on GitHub but not on CRAN, the official repository for R packages. Also, note that we did not explicitly load the whole devtools library, but we simply picked out the function we needed.

Don’t forget to load these newly installed packages 😉

Now we must use the whole dataset (saved as att_filter_select_recode_long_sep_onego), not the data frame with the summary statistics we used for the bar plots (summary_att_filter_select_recode_long_sep_onego).

Here is the code for the plot:

The plot can be saved with the following command:

Exercise 3

Exercise 3.0

Load data_attitude_wine.csv

Exercise 3.1

Create a plot similar to what is shown above (with wine instead of beer) and save it in the subfolder images

Exercise 3.2

The same as above, separately for female and male participants (hint: use facet_wrap)

Exercise 3 BONUS

Recreate a plot similar to #2 using the yarrr package (warning: saving the plot to file can be tricky 😉). Check out YaRrr! The Pirate’s Guide to R for help.

Data analysis

The aim of this study was to assess whether negative imagery would influence the likeness ratings of alcoholic beverages. It’s time to test this hypothesis statistically.

We will run a 2 (drink: water, beer) x 2 (imagery: neutral, negative) repeated measures ANOVA on these ratings.

For this demonstration I chose the package afex, authored by Henrik Singmann.

Repeated measures ANOVA

The code below shows how to run an ANOVA with this versatile and user-friendly package.

## Anova Table (Type 3 tests)
## 
## Response: ratings
##          Effect    df    MSE         F ges p.value
## 1         drink 1, 19 252.84   8.97 ** .19    .007
## 2       imagery 1, 19  82.92 17.63 *** .13   .0005
## 3 drink:imagery 1, 19  26.66    6.75 * .02     .02
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1

The results show:

  • a statistically significant main effect of drink (F(1, 19) = 8.97, p = 0.007, \(\eta\)2G = 0.19)
  • a statistically significant main effect of imagery (F(1, 19) = 17.63, p = 0.0005, \(\eta\)2G = 0.13)
  • a statistically significant drink x imagery interaction (F(1, 19) = 6.75, p = 0.018, \(\eta\)2G = 0.02)

Paired contrasts

The drink x imagery interaction is statistically significant… let’s run paired comparisons. afex uses functions included in the emmeans package.

## 
##   Simultaneous Tests for General Linear Hypotheses
## 
## Linear Hypotheses:
##                                     Estimate Std. Error t value Pr(>|t|)    
## negative,beer - neutral,beer == 0     -5.550      2.604  -2.131   0.1425    
## negative,beer - negative,water == 0   13.650      4.329   3.153   0.0190 *  
## negative,beer - neutral,water == 0     2.100      4.997   0.420   0.9613    
## neutral,beer - negative,water == 0    19.200      2.934   6.544   <0.001 ***
## neutral,beer - neutral,water == 0      7.650      3.034   2.521   0.0689 .  
## negative,water - neutral,water == 0  -11.550      2.044  -5.652   <0.001 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## (Adjusted p values reported -- single-step method)

Results show7:

  • a statistically significant difference (p = 0.019) between ratings of beer and water after negative imagery –> after negative advertisement, people (still) rate beer as more pleasant than water
  • a statistically significant difference (p = 0.00006) between ratings of water after neutral compared to negative imagery –> water was rated as less pleasant after negative compared to neutral advertisement

Interestingly, beer ratings between negative and neutral imagery are not statistically significant (p = 0.143). This might indicate that the experimental manipulation did not have the intended effect, although such a conclusion cannot be inferred from the non-significant p-value alone.

The output of rmANOVA_att and posthoc_att is almost publication-ready… almost. Something is missing.

Effect sizes

It is good practice to report effect sizes along with p-values, so that readers can make their own mind with respect to the importance of the observed effects. Even better, you could report confidence intervals around effect sizes, so that readers can have a clear picture of the precision of your estimation.

I particularly like the idea of bootstrapping effect sizes, a better approach when the data are known not to be normally distributed or when the distribution is unknown8. I will show you how to do it using the package bootES9.

We will compute Hegdes’ g, an unbiased estimate of \(\delta\) (for details, see here).

Because our dependent variable consists of ratings collected from the same participants in different conditions (i.e., repeated measures), we must first manually compute the difference scores between our contrasts of interest (see the output of the paired comparisons above).

Now we can calculate the standardized effect size for each difference scores. Using functions in the purrr package (part of the tidyverse!), we will create separate lists for each difference score and calculate bootstrapped Hegdes’s g for each of them.

## # A tibble: 6 x 6
##   diff_conds                    Hedges_g CI95_low CI95_high     bias std_error
##   <chr>                            <dbl>    <dbl>     <dbl>    <dbl>     <dbl>
## 1 beer_negativeVSbeer_neutral    -0.457    -1.06    -0.0514 -0.0407      0.256
## 2 beer_negativeVSwater_negative   0.677     0.297    1.23    0.0324      0.237
## 3 beer_negativeVSwater_neutral    0.0902   -0.368    0.526  -0.00203     0.224
## 4 beer_neutralVSwater_negative    1.40      0.938    2.32    0.0916      0.353
## 5 beer_neutralVSwater_neutral     0.541     0.134    1.10    0.0278      0.246
## 6 water_negativeVSwater_neutral  -1.21     -2.92    -0.676  -0.156       0.536

The output (att_HedgesG) is a data frame containing the results of the bootstrapping procedure for each diff_conds.

This is a very flexible and powerful approach, which can be used to run all kinds of operations to subsets of your data. See an example here on how to run many linear models simultaneously.

Exercise 4

Exercise 4.1

Load data_attitude_wine.csv.

Exercise 4.1.1

Run a 2 (drink) x 2 (imagery) repeated measures ANOVA on likeness ratings and display the results in console.

Exercise 4.1.2

Run paired contrasts and display the results in console.

Exercise 4.1.3

Run bootstrapped effect sizes (calculate Pearson’s r instead of Hegdes’s g) and display the results in console.

Exercise 4.2

Exercise 4.2.1

Run a 2 (gender) x 2 (drink) x 2 (imagery) mixed ANOVA on likeness ratings. Remember: gender is a between-subject factor!

Exercise 4.2.2

Paired contrasts: test only difference ratings between female and male participants (hint: see example here).

Exercise 4.2.3

Bootstrapped effect sizes (Cohen’s d) of the paired comparisons above.

Session Info

You have now successfully used the tidyverse to load, preprocess, plot, and analyze your data. Even better, you have done it in an environment that facilitates reproducibility: you only need the raw data and the .Rmd file to reproduce the figures and the statistical results.

However, I said facilitate for a reason: even using this workflow, computational reproducibility is not guaranteed. For example, a specific R package might drastically change its functionalities so that the syntax is no longer valid, or a colleague may be using a different operating system which relies on different libraries.

There are ways to (almost) ensure computational reproducibility. The best option I have found so far is to create an R package with data, preprocessing and analysis scripts, and files that document the specific version of each package used for the computations. This package can be embedded into a container, a sort of virtual machine that contains an operating system with its own software, libraries, and configuration files. Learning these skills require some time but, in my opinion, it’s worth the time and effort. If you are interested, check out rrtools.

Another good (and low-effort 😄) option is to use the function sessonInfo, which lists important information related to your operating system and libraries as well as R and package versions.

## R version 3.6.2 (2019-12-12)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.4 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=nl_NL.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=nl_NL.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=nl_NL.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=nl_NL.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] broom_0.5.4       bootES_1.2        boot_1.3-24       emmeans_1.4.4    
##  [5] afex_0.26-0       lme4_1.1-21       Matrix_1.2-18     ggpirate_0.1.1   
##  [9] viridis_0.5.1     viridisLite_0.3.0 emo_0.0.0.9000    forcats_0.4.0    
## [13] stringr_1.4.0     dplyr_0.8.4       purrr_0.3.3       readr_1.3.1      
## [17] tidyr_1.0.2       tibble_2.1.3      ggplot2_3.2.1     tidyverse_1.3.0  
## [21] here_0.1          devtools_2.2.2    usethis_1.5.1     knitr_1.28       
## 
## loaded via a namespace (and not attached):
##  [1] TH.data_1.0-10      minqa_1.2.4         colorspace_1.4-1   
##  [4] ellipsis_0.3.0      rio_0.5.16          rprojroot_1.3-2    
##  [7] estimability_1.3    fs_1.3.1            rstudioapi_0.11    
## [10] farver_2.0.3        remotes_2.1.1       fansi_0.4.1        
## [13] mvtnorm_1.0-12      lubridate_1.7.4     xml2_1.2.2         
## [16] codetools_0.2-16    splines_3.6.2       pkgload_1.0.2      
## [19] jsonlite_1.6.1      nloptr_1.2.1        dbplyr_1.4.2       
## [22] compiler_3.6.2      httr_1.4.1          backports_1.1.5    
## [25] assertthat_0.2.1    lazyeval_0.2.2      cli_2.0.1          
## [28] htmltools_0.4.0     prettyunits_1.1.1   tools_3.6.2        
## [31] lmerTest_3.1-1      coda_0.19-3         gtable_0.3.0       
## [34] glue_1.3.1          reshape2_1.4.3      Rcpp_1.0.3         
## [37] carData_3.0-3       cellranger_1.1.0    vctrs_0.2.2        
## [40] nlme_3.1-144        xfun_0.12           ps_1.3.2           
## [43] openxlsx_4.1.4      testthat_2.3.1      rvest_0.3.5        
## [46] lifecycle_0.1.0     zoo_1.8-7           MASS_7.3-51.5      
## [49] scales_1.1.0        hms_0.5.3           sandwich_2.5-1     
## [52] parallel_3.6.2      yaml_2.2.1          curl_4.3           
## [55] memoise_1.1.0       gridExtra_2.3       stringi_1.4.6      
## [58] desc_1.2.0          pkgbuild_1.0.6      zip_2.0.4          
## [61] rlang_0.4.4         pkgconfig_2.0.3     evaluate_0.14      
## [64] lattice_0.20-38     labeling_0.3        processx_3.4.2     
## [67] tidyselect_1.0.0    plyr_1.8.5          magrittr_1.5       
## [70] R6_2.4.1            generics_0.0.2      multcomp_1.4-12    
## [73] DBI_1.1.0           pillar_1.4.3        haven_2.2.0        
## [76] foreign_0.8-75      withr_2.1.2         survival_3.1-8     
## [79] abind_1.4-5         modelr_0.1.5        crayon_1.3.4       
## [82] car_3.0-6           utf8_1.1.4          rmarkdown_2.1      
## [85] grid_3.6.2          readxl_1.3.1        data.table_1.12.8  
## [88] callr_3.4.2         reprex_0.3.0        digest_0.6.24      
## [91] xtable_1.8-4        numDeriv_2016.8-1.1 munsell_0.5.0      
## [94] sessioninfo_1.1.1

Conclusion

I hope to have given you a glimpse of the versatility, readability, and user-friendliness of the tidyverse, and inspired you to work in a reproducible environment to benefit your future self and other colleagues. Enjoy your tidy, reproducible new life!


Thanks!




  1. Hopefully you’re not familiar with pretending to collect data… if so, please tell your story by writing a book.

  2. As you may imagine, today we won’t have time to cover all the amazing things you can do with these packages. Also, they are a gift that keeps on giving: I have been using them for a while and I keep discovering useful functions. If you want to learn more, read R for Data Science by Garrett Grolemund and Hadley Wickham.

  3. It is good to know where your packages are. Type .libPaths() in the RStudio console to find out.

  4. When you have no idea where to start, Google (or its privacy-oriented alternative StartPage) and StackOverflow are your friends!

  5. This is a modified version of a data set included in the book Discovering Statistics Using R (Field, Miles & Field, 2012).

  6. These RDI plots are sometimes called pirateplots, in honor of Nathaniel D. Phillips’s book YaRrr! The Pirate’s Guide to R. If you are curious, check out the yarrr package.

  7. Another statistically significant finding (ratings of beer after neutral imagery vs. ratings of water after negative imagery) is not of interest for our research question, whereas the ratings difference between beer and water after neutral imagery is only close to the conventional threshold of p = 0.05. This result is not-significant. It does not “approach significance”, there is no “trend toward significance”, or any other creative way to describe a non-significant finding in a way that will increase your chances of publication. For a fun take on the subject, see this blog.

  8. If you prefer not to bootstrap your effect sizes, you can use the MBESS package (a useful tutorial can be found here).

  9. A clear explanation of how to use bootES is provided by the authors of the package in their paper.

 

Antonio Schettino

schettino@eur.nl